//
//  GXCycleImage.m
//  16-UICollectionViewCycleImage
//
//  Created by Snow on 16/8/4.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "GXCycleImage.h"


#define kColor [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1]
#define Reuse @"cell"

@interface GXCycleImage ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSTimer *time;
@property (nonatomic, assign) NSInteger index;

@end


@implementation GXCycleImage
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setup];
        
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor greenColor];
        [self setup];
        NSLog(@"%lf", self.frame.size.width);
    }
    return self;
}
- (void)setup
{
    [self createCollectionView];
    [self createPageControl];
    [self createTimer];
   
}
- (void)createCollectionView
{
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;
    [self addSubview:_cycleCollectionView];
    [_cycleCollectionView registerClass:[GXCycleImageCell class] forCellWithReuseIdentifier:Reuse];
    [_cycleCollectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
}
- (void)createPageControl
{
    _pageControl = [[UIPageControl alloc] init];
    [self addSubview:_pageControl];
    [_pageControl addTarget:self action:@selector(pageControl:) forControlEvents:UIControlEventValueChanged];
    
}



// 子控件重新布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    _cycleCollectionView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    _cycleCollectionView.contentOffset = CGPointMake(self.frame.size.width, 0);
    _flowLayout.itemSize = _cycleCollectionView.bounds.size;
    
    _pageControl.frame = CGRectMake(self.frame.size.width / 3, self.frame.size.height - 20, self.frame.size.width / 3, 20);
   
}



// collection的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _arrayImage.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GXCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Reuse forIndexPath:indexPath];
    cell.cycleImage.image =[UIImage imageNamed:[_arrayImage objectAtIndex:indexPath.row]];
    cell.lable.text = @"广告";
//    cell.backgroundColor = kColor;
    return cell;
}


// collectionView的协议点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    GXCycleImageCell *cell =(UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//    cell.cycleImage.image
    if ([self.delegate respondsToSelector:@selector(backOneNsstring)]) {
        NSString *back = [self.delegate backOneNsstring];
        [_arrayImage replaceObjectAtIndex:indexPath.row withObject:back];
        [_cycleCollectionView reloadData];
    }
    
    
}




//set 赋值
- (void)setArrayImage:(NSMutableArray *)arrayImage
{
    NSString *first = [arrayImage firstObject];
    NSString *last = [arrayImage lastObject];
    [arrayImage insertObject:last atIndex:0];
    [arrayImage addObject:first];
    
    _arrayImage = arrayImage;
    _pageControl.numberOfPages = _arrayImage.count - 2;
    [_cycleCollectionView reloadData];
    
}

// 实现轮播效果
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == 0) {
        //        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width * (_arrayImage.count - 2), 0)];
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_arrayImage.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        _pageControl.currentPage = _arrayImage.count - 3;
    } else if (scrollView.contentOffset.x == _cycleCollectionView.bounds.size.width * (_arrayImage.count - 1)) {
        //        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width, 0)];
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        _pageControl.currentPage = 0;
    }
    
    _pageControl.currentPage = scrollView.contentOffset.x / self.frame.size.width - 1;
    
}
// pagecontrol的执行方法

- (void)pageControl:(UIPageControl *)page
{
    [_cycleCollectionView setContentOffset:CGPointMake(self.frame.size.width * (page.currentPage + 1), 0) animated:YES];
}

// 添加定时器

- (void)createTimer
{
    self.index = 1;
    
    // 这个只是创建一timer , 并没有加在loop中
//    _time = [NSTimer TimerWithTimeInterval:2 target:self selector:@selector(timeHandle:) userInfo:nil repeats:YES];
    
    
    //  创建一个timer,, 并添加到loop中
    _time = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timeHandle:) userInfo:nil repeats:YES];
    
    //NSDefaultRunLoopMode  与   NSRunLoopCommonModes
    //区别: 1. 前者代表默认状态 scheduledTimerWithTimeInterval添加为默认状态
    //     2. 后者为多种状态 包含默认 以及 滚动
    
//    [[NSRunLoop currentRunLoop] addTimer:_time forMode:NSRunLoopCommonModes];
    
    
    [_time invalidate];
    _time = nil;
    
}

// 移除timer
- (void)removeTimer
{
    [_time invalidate];
    _time = nil;

}


// time 方法

- (void)timeHandle:(NSTimer *)time
{
    [UIView animateWithDuration:0.5 animations:^{
        
        
    }];
    _pageControl.currentPage = _index;
    [self pageControl:_pageControl];
    
    self.index++;
    
    if (_index == _arrayImage.count - 2) {
        _index = 0;
        
    }

}



@end




@implementation GXCycleImageCell
- (instancetype) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
        
        _lable = [[UILabel alloc] initWithFrame:CGRectMake(self.bounds.size.width / 3, 0, self.bounds.size.width / 3, 30)];
        _lable.textAlignment = 1;
        [self.contentView addSubview:_lable];
    }
    return self;
}


@end



